﻿define(["common"], function (app) {
    app.factory('AccountService', ["$http", "$rootScope", "$q", function ($http, $rootScope, $q) {
        var service = {
            currentAccount: null,
            refresh: function () {
                var deferred = $q.defer();

                $http.get("/dashboard/services/account")
                    .success(function (data) {
                        $rootScope.currentAccount = data;

                        // parse the date, which is dd/MM/yyyy
                        if (data.DateOfBirth) {
                            var date;
                            try {
                                date = new Date(
                                    parseInt(data.DateOfBirth.substring(6, 10)),
                                    parseInt(data.DateOfBirth.substring(3, 5)) - 1,
                                    parseInt(data.DateOfBirth.substring(0, 2)));
                            }
                            catch (err) {
                                date = new Date();
                            }

                            $rootScope.currentAccount.DateOfBirth = date;
                        }

                        deferred.resolve();
                    });
                
                return deferred.promise;
            }
        };

        return service;
    }]);
    return null;
});